// DeviceManager.cpp
#include "DeviceManager.h"
#include "DatabaseManager.h"
#include <unordered_map>
#include <iostream>
#include <string>
#include <memory>

using namespace std;


// 定义枚举到字符串的映射
std::unordered_map<Device::DeviceType, std::string> deviceTypeToString = {
    {Device::DeviceType::LIGHT, "LIGHT"},
    {Device::DeviceType::THERMOSTAT, "THERMOSTAT"},
    {Device::DeviceType::CAMERA, "CAMERA"}
    // 添加其他设备类型
};

// 静态实例初始化
DeviceManager& DeviceManager::getInstance() {
    static DeviceManager instance;
    return instance;
}

// 构造函数
DeviceManager::DeviceManager() {
    // 初始化代码（如果需要）
}

DeviceManager::~DeviceManager() {
    // 析构函数实现
}


// 添加设备
void DeviceManager::addDevice(const Device& device) {
    // 根据设备类型创建具体设备类的实例
    std::unique_ptr<Device> newDevice;
    switch (device.getType()) {
        case Device::DeviceType::LIGHT:
            newDevice = std::make_unique<Light>(device.getId());
            break;
        case Device::DeviceType::THERMOSTAT:
            newDevice = std::make_unique<Thermostat>(device.getId());
            break;
        case Device::DeviceType::CAMERA:
            newDevice = std::make_unique<Camera>(device.getId());
            break;
        case Device::DeviceType::SOCKET:
            newDevice = std::make_unique<Socket>(device.getId());
            break;
        default:
            cerr << "错误:未知设备类型" << endl;
            return;
    }

    // 设置设备状态
    newDevice->setStatus(device.getStatus());

    // 插入到设备管理器的映射中
    devices.emplace(device.getId(), std::move(newDevice));

    // 获取数据库管理器实例
    DatabaseManager& dbManager = DatabaseManager::getInstance();

    // 将枚举类型转换为字符串
    std::string deviceTypeStr = deviceTypeToString[device.getType()];

    // 构造插入语句，使用参数化查询
    sqlite3_stmt* stmt;
    string insertQuery = "INSERT INTO devices (id, device_type, status, last_modified) VALUES (?,?,?, CURRENT_TIMESTAMP);";
    if (sqlite3_prepare_v2(dbManager.getDB(), insertQuery.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
        sqlite3_bind_int(stmt, 1, device.getId());
        sqlite3_bind_text(stmt, 2, deviceTypeStr.c_str(), -1, SQLITE_STATIC);
        sqlite3_bind_text(stmt, 3, device.getStatus().c_str(), -1, SQLITE_STATIC);
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            cout << "设备添加成功" << endl;
        } else {
            cerr << "错误:设备添加失败" << endl;
        }
        sqlite3_finalize(stmt);
    } else {
        cerr << "错误:准备插入语句失败" << endl;
    }
}

// 移除设备
void DeviceManager::removeDevice(int deviceId) {
    if (devices.find(deviceId) != devices.end()) {
        devices.erase(deviceId);

        // 获取数据库管理器实例
        DatabaseManager& dbManager = DatabaseManager::getInstance();
        // 构造删除语句，使用参数化查询
        sqlite3_stmt* stmt;
        string deleteQuery = "DELETE FROM devices WHERE id = ?;";
        if (sqlite3_prepare_v2(dbManager.getDB(), deleteQuery.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
            sqlite3_bind_int(stmt, 1, deviceId);
            if (sqlite3_step(stmt) == SQLITE_DONE) {
                cout << "设备删除成功,设备 ID:" << deviceId << endl;
            } else {
                cerr << "错误:设备删除失败" << endl;
            }
            sqlite3_finalize(stmt);
        } else {
            cerr << "错误:准备删除语句失败" << endl;
        }
    } else {
        cerr << "错误:设备未找到" << endl;
    }
}

// 获取设备
Device* DeviceManager::getDevice(int deviceId) {
    if (devices.find(deviceId) != devices.end()) {
        return devices[deviceId].get();  // 返回智能指针管理的原始指针
    } else {
        cerr << "错误:设备未找到" << endl;
        return nullptr;
    }
}

// 更新设备状态
void DeviceManager::updateDeviceStatus(int deviceId, const string& newStatus) {
    if (devices.find(deviceId) != devices.end()) {
        devices[deviceId]->setStatus(newStatus);

        // 获取数据库管理器实例
        DatabaseManager& dbManager = DatabaseManager::getInstance();
        // 构造更新语句，使用参数化查询
        sqlite3_stmt* stmt;
        string updateQuery = "UPDATE devices SET status = ?, last_modified = CURRENT_TIMESTAMP WHERE id = ?;";
        if (sqlite3_prepare_v2(dbManager.getDB(), updateQuery.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
            sqlite3_bind_text(stmt, 1, newStatus.c_str(), -1, SQLITE_STATIC);
            sqlite3_bind_int(stmt, 2, deviceId);
            if (sqlite3_step(stmt) == SQLITE_DONE) {
                cout << "设备状态更新成功，设备 ID:" << deviceId << endl;
            } else {
                cerr << "错误:设备状态更新失败" << endl;
            }
            sqlite3_finalize(stmt);
        } else {
            cerr << "错误:准备更新语句失败" << endl;
        }
    } else {
        cerr << "错误:设备未找到" << endl;
    }
}

// 使用 vector 存储 Device 指针
vector<Device*> DeviceManager::getAllDevices() const {
    vector<Device*> deviceList;
    for (const auto& pair : devices) {
        deviceList.push_back(pair.second.get());  // 获取智能指针管理的原始指针
    }
    return deviceList;
}

// 批量禁用设备
void DeviceManager::batchDisableDevices(const std::vector<int>& deviceIds) {
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    sqlite3_stmt* stmt;
    string updateQuery = "UPDATE devices SET status = 'off', last_modified = CURRENT_TIMESTAMP WHERE id = ?;";

    if (sqlite3_prepare_v2(dbManager.getDB(), updateQuery.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
        for (int deviceId : deviceIds) {
            if (devices.find(deviceId) != devices.end()) {
                devices[deviceId]->setStatus("off");
                sqlite3_reset(stmt);
                sqlite3_bind_int(stmt, 1, deviceId);
                if (sqlite3_step(stmt) == SQLITE_DONE) {
                    cout << "设备禁用成功，设备 ID:" << deviceId << endl;
                } else {
                    cerr << "错误:设备禁用失败，设备 ID:" << deviceId << endl;
                }
            } else {
                cerr << "错误:设备未找到，设备 ID:" << deviceId << endl;
            }
        }
        sqlite3_finalize(stmt);
    } else {
        cerr << "错误:准备更新语句失败" << endl;
    }
}

// 批量启用设备
void DeviceManager::batchEnableDevices(const std::vector<int>& deviceIds) {
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    sqlite3_stmt* stmt;
    string updateQuery = "UPDATE devices SET status = 'on', last_modified = CURRENT_TIMESTAMP WHERE id = ?;";

    if (sqlite3_prepare_v2(dbManager.getDB(), updateQuery.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
        for (int deviceId : deviceIds) {
            if (devices.find(deviceId) != devices.end()) {
                devices[deviceId]->setStatus("on");
                sqlite3_reset(stmt);
                sqlite3_bind_int(stmt, 1, deviceId);
                if (sqlite3_step(stmt) == SQLITE_DONE) {
                    cout << "设备启用成功，设备 ID:" << deviceId << endl;
                } else {
                    cerr << "错误:设备启用失败，设备 ID:" << deviceId << endl;
                }
            } else {
                cerr << "错误:设备未找到，设备 ID:" << deviceId << endl;
            }
        }
        sqlite3_finalize(stmt);
    } else {
        cerr << "错误:准备更新语句失败" << endl;
    }
}
